﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text.RegularExpressions;

namespace HitchHikersGuideToTheGalaxy.Helpers
{
    public class SSNValidator
    {

        /// <summary>
        /// Vartölu tékk frá Hagstofunni.
        /// </summary>
        /// <param name="ssn"></param>
        /// <returns></returns>
        public static bool IsValidSSN(String ssn)
        {
            String kennit = ssn;

            // pattern to ensure we only have ten digits as input...
            Regex kennitalaPattern = new Regex("[0-9]{10}");

            // first sanity check..
            if (ssn.Length == null)
            {
                return false;
            }
            // second sanity check...
            if (ssn.Contains("-"))
            {
                return false;
            }
            // third sanity check...
            if (!kennitalaPattern.IsMatch(ssn))
            {
                return false;
            }

            // we should be okay by now, so let's start working on the input...
            int sum = Convert.ToInt32(kennit.Substring(0, 1)) * 3;
            sum = sum + Convert.ToInt32(kennit.Substring(1, 1)) * 2;
            sum = sum + Convert.ToInt32(kennit.Substring(2, 1)) * 7;
            sum = sum + Convert.ToInt32(kennit.Substring(3, 1)) * 6;
            sum = sum + Convert.ToInt32(kennit.Substring(4, 1)) * 5;
            sum = sum + Convert.ToInt32(kennit.Substring(5, 1)) * 4;
            sum = sum + Convert.ToInt32(kennit.Substring(6, 1)) * 3;
            sum = sum + Convert.ToInt32(kennit.Substring(7, 1)) * 2;

            // let's find out what vartala we got...
            int vartala = 11 - (sum % 11);

            // vartala should equal kennit.Substring(8, 1)
            if (vartala == Convert.ToInt32(kennit.Substring(8, 1)))
            {
                return true;
            }
            else
            {
                if (vartala == 11)
                {
                    if (0 == Convert.ToInt32(kennit.Substring(8, 1)))
                    {
                        return true;
                    }
                    else
                    {
                        return false; // kennitala is not correct
                    }
                }
                else
                {
                    return false; // kennitala is not correct
                }
            }
        }

    }
}
